<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">高校员工餐饮系统</h2>
      <!-- 登录表单 -->
      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        label-width="80px"
        class="login-form"
      >
        <!-- 角色选择 -->
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="loginForm.role" @change="handleRoleChange">
            <el-radio label="管理员">管理员</el-radio>
            <el-radio label="商家">商家</el-radio>
            <el-radio label="教职工">教职工</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 工号输入框 -->
        <el-form-item label="工号" prop="WorkId">
          <el-input
            v-model="loginForm.WorkId"
            :placeholder="`请输入${loginForm.role}工号（如：${getRoleExample(loginForm.role)}）`"
            prefix-icon="el-icon-user"
            clearable
          />
        </el-form-item>
        
        <!-- 密码输入框 -->
        <el-form-item label="密码" prop="Password">
          <el-input
            v-model="loginForm.Password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
            clearable
          />
        </el-form-item>
        
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            @click="handleLogin"
            :loading="loading"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';
import type { LoginRequest, LoginBackendResponse } from '@/types/index';
import type { ElForm } from 'element-plus';

const router = useRouter();
const route = useRoute();
const loginFormRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(false);

// 定义角色类型
type RoleType = '管理员' | '商家' | '教职工';

// 角色示例工号
const roleExample: Record<RoleType, string> = {
  '管理员': 'A001',
  '商家': 'M001',
  '教职工': 'T001'
};

// 获取角色示例（修复类型错误的关键）
const getRoleExample = (role: string): string => {
  if (role in roleExample) {
    return roleExample[role as RoleType];
  }
  return '';
};

const loginForm = reactive<LoginRequest & { role: RoleType }>({
  role: '教职工',
  WorkId: '',
  Password: ''
});

// 预设账号密码（本地验证用）
const presetAccounts: Record<RoleType, { workId: string; password: string; userName: string }> = {
  '管理员': { workId: 'A001', password: 'admin123', userName: '系统管理员' },
  '商家': { workId: 'M001', password: 'mypass123', userName: '阳光餐厅' },
  '教职工': { workId: '', password: '', userName: '' } // 占位，实际由后端验证
};

const loginRules = reactive({
  role: [
    { required: true, trigger: 'change', message: '请选择角色' }
  ],
  WorkId: [
    { required: true, trigger: 'blur', message: '请输入工号' },
    { min: 3, max: 20, trigger: 'blur', message: '工号长度为 3-20 个字符' }
  ],
  Password: [
    { required: true, trigger: 'blur', message: '请输入密码' },
    { min: 6, max: 20, trigger: 'blur', message: '密码长度为 6-20 个字符' }
  ]
});

// 角色改变时自动填充示例账号
const handleRoleChange = () => {
  if (loginForm.role === '管理员') {
    loginForm.WorkId = 'A001';
    loginForm.Password = 'admin123';
  } else if (loginForm.role === '商家') {
    loginForm.WorkId = 'M001';
    loginForm.Password = 'mypass123';
  } else {
    loginForm.WorkId = '';
    loginForm.Password = '';
  }
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate();
    loading.value = true;
    
    // 区分处理不同角色的登录逻辑
    if (loginForm.role === '管理员' || loginForm.role === '商家') {
      // 本地验证（不调用后端）
      const preset = presetAccounts[loginForm.role];
      
      if (loginForm.WorkId === preset.workId && loginForm.Password === preset.password) {
        // 构造本地用户数据
        const userData = {
          workId: preset.workId,
          userName: preset.userName,
          role: loginForm.role
        };
        
        // 存储数据
        localStorage.setItem('token', 'local-token-' + loginForm.role);
        localStorage.setItem('user', JSON.stringify(userData));
        
        // 跳转逻辑
        const redirectPath = route.query.redirect as string;
        if (redirectPath) {
          router.push(redirectPath);
        } else {
          // 管理员跳转到教职工管理页面，商家跳转到商家管理页面
          router.push(loginForm.role === '管理员' ? '/user/teachers' : '/merchant/manage');
        }
        
        ElMessage.success('登录成功！');
      } else {
        throw new Error('账号或密码错误');
      }
    } else {
      // 教职工登录（保持原逻辑，调用后端）
      const res: LoginBackendResponse = await request.post('/api/Auth/login', loginForm);
      
      // 存储数据
      localStorage.setItem('token', res.token);
      localStorage.setItem('user', JSON.stringify(res.user));
      
      // 跳转逻辑
      const redirectPath = route.query.redirect as string;
      if (redirectPath) {
        router.push(redirectPath);
      } else {
        router.push('/user');
      }
      
      ElMessage.success(res.message || '登录成功！');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败，请检查账号密码！');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 420px;
  padding: 30px 40px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 25px;
  color: #1989fa;
  font-size: 24px;
  font-weight: 600;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.el-radio-group {
  display: flex;
  gap: 20px;
}
</style>